/*
 * SHOPTNT 版权所有。
 * 未经许可，您不得使用此文件。
 * 官方地址：www.shoptnt.cn
 */
package cn.shoptnt.service.member.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.shoptnt.client.system.FalsifyRecordClient;
import cn.shoptnt.service.passport.signaturer.SignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.shoptnt.framework.util.DateUtil;
import cn.shoptnt.mapper.member.MemberWalletMapper;
import cn.shoptnt.model.member.dos.MemberWalletDO;
import cn.shoptnt.model.security.*;
import cn.shoptnt.service.member.MemberWalletManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 会员预存款业务类
 *
 * @author zs
 * @version v1.0
 * @since v7.0.0
 * 2021-12-21
 */
@Service
public class MemberWalletManagerImpl implements MemberWalletManager {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private MemberWalletMapper memberWalletMapper;

    @Autowired
    private FalsifyRecordClient falsifyRecordClient;

    @Override
    public MemberWalletDO getByMemberId(Long memberId) {
        return new QueryChainWrapper<>(memberWalletMapper).eq("member_id", memberId).one();
    }

    @Override
    public ScanResult scanModule(ScanModuleDTO scanModuleDTO) {
        QueryWrapper queryWrapper = scanModuleDTO.getQueryWrapper();
        Long pageSize = scanModuleDTO.getPageSize();
        String rounds = scanModuleDTO.getRounds();
        IPage<MemberWalletDO> walletPage = memberWalletMapper.selectPage(new Page(1, pageSize), queryWrapper);
        List<MemberWalletDO> walletList = walletPage.getRecords();
        ScanResult scanResult = new ScanResult();

        boolean signResult = true;

        for (MemberWalletDO memberWallet : walletList) {


            UpdateChainWrapper upw = new UpdateChainWrapper<>(memberWalletMapper)
                    //设置会员钱包状态
                    .set("scan_rounds", rounds);
            upw.set("sign_result", 1);
            upw.eq("id", memberWallet.getId());
            upw.update();

        }

        scanResult.setSuccess(signResult);
        scanResult.setComplete(walletList.size() == 0);
        return scanResult;
    }

    @Override
    public void reSign() {
        List<MemberWalletDO> memberList = memberWalletMapper.selectList(null);
        for (MemberWalletDO memberWalletDO : memberList) {
            memberWalletMapper.updateById(memberWalletDO);
        }
    }

    @Override
    public void repair(Long memberWalletId) {
        MemberWalletDO memberWalletDO = memberWalletMapper.selectById(memberWalletId);
        memberWalletMapper.updateById(memberWalletDO);
    }
}
